package MooseX::CLI::Command::Help::Commands;

use Any::Moose '::Role';

requires qw( _cmd_base_class _get_cmd_package_filename );


use Smart::Comments;

use Pod::Simple::Text;

use Exception::CLI;


sub show_help {
    my $self = shift;

    my $base = $self->_cmd_base_class;
    ### $base

    require all;
    all->import($base . '::*');

    my $msg = "Available commands:\n";

    my @classes = any_moose eq 'Moose'
                  ? Class::MOP::get_all_metaclass_names()
                  : Mouse::Util::get_all_metaclass_names();
    @classes = sort
                  grep {
                      /^\Q$base\E::(\w+)$/
                      and $_->isa(any_moose('::Object'))
                      and $_->does('MooseX::CLI::Command')
                      and not $_->does('MooseX::CLI::Role::Alias')
                  } @classes;

    foreach my $class (@classes) {
        ### $class
        my $filename = $INC{ $self->_get_cmd_package_filename( $class ) };
        ### $filename

        my $usage = $self->_cmd_brief_usage($filename);
        $msg .= "    $usage\n" if $usage;
    };

    Exception::CLI->throw( message => $msg );
};


sub _cmd_brief_usage {
    my ($self, $filename) = @_;
    my $base = $self->_cmd_base_class;
    ### assert: $base

    open my ($fh), '<', $filename or return;
    local $/ = undef;
    my $buf = <$fh>;
    my $msg;
    if($buf =~ /^=head1\s+NAME\s*\Q$base\E::(\w+ - .+)$/m) {
        $msg = lcfirst($1);
    };
    close $fh;

    return $msg;
};


1;
